<template>
	<div class="index-tablist-box" :key="props.classifyId">
		<!-- 滚动容器：必须设置固定高度 -->
		<div class="scroll-container" ref="scrollContainer">
			<div v-if="loading && dataList.length === 0">
				<PageLoading ></PageLoading>
			</div>
			<div v-else class="list-box">
				<CoverImage class="itembox" v-for="(item, index) in dataList" :key="index"
					@click="goToDetail(item.courseId)" :item="item" :cache="false"></CoverImage>
			</div>
			<div class="load-status" v-show="isLoadingMore">
			  加载中...
			</div>
			<div class="load-status"v-show="!loadMoreStatus && !isLoadingMore">
				————&nbsp;&nbsp;&nbsp;&nbsp;啊呀~到底了呢&nbsp;&nbsp;&nbsp;&nbsp;————
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		defineExpose,
		watch,
		onMounted,
		onUnmounted,
		nextTick
	} from 'vue';
	import {
		useRouter,
		useRoute
	} from 'vue-router';
	import {
		getCommicList
	} from '@/api/index.js';
	import {
		debounce
	} from 'lodash';
	import PageLoading from '../PageLoading.vue';
	import CoverImage from '../CoverImage';
	const router = useRouter();
	const route = useRoute();

	const props = defineProps({
		classifyId: {
			type: String,
			required: true
		}
	});

	// 核心状态
	const dataList = ref([]);
	// const isPageLoading = ref(true); 
	const pageInfo = ref({
		page: 1,
		limit: 9,
		totalPage: null
	});
	const loading = ref(false); // 初始加载状态
	const localClassifyId = ref(0);
	const lastScrollTop = ref(0);
	const loadMoreStatus = ref(true); // 'more'/'loading'/'nomore'
	const scrollContainer = ref(null); // 滚动容器引用
	let isLoadingMore = false; // 防止重复请求（局部变量，不响应式）

	// 初始加载/刷新数据
	const getData = async () => {
		loading.value = true;
		// dataList.value.length = 0;
		try {
			const result = await getCommicList({
				page: 1,
				limit: pageInfo.value.limit,
				classifyId: localClassifyId.value,
				sort: 1
			});
			const res = result.data;
			dataList.value = res.list;
			pageInfo.value = {
				...pageInfo.value,
				totalPage: res.totalPage,
				page: res.currPage
			};
			loadMoreStatus.value = res.totalPage > res.currPage;
		} catch (err) {
			console.error('初始加载失败:', err);
			
		} finally {
			loading.value = false;
		}
	};

	// 上拉加载更多
	const loadMore = async () => {
		// 阻止重复请求或已到底
		if (isLoadingMore || pageInfo.value.page >= pageInfo.value.totalPage) {
			loadMoreStatus.value = false;
			return;
		}

		isLoadingMore = true;
		loadMoreStatus.value = true;
		try {
			const result = await getCommicList({
				page: pageInfo.value.page + 1,
				limit: pageInfo.value.limit,
				classifyId: localClassifyId.value,
				sort: 1
			});
			const res = result.data;
			dataList.value = [...dataList.value, ...res.list];
			pageInfo.value = {
				...pageInfo.value,
				totalPage: res.totalPage,
				page: res.currPage
			};
			loadMoreStatus.value = res.currPage < res.totalPage;
		} catch (err) {
			loadMoreStatus.value = true;  // 失败后允许重试
		} finally {
			isLoadingMore = false;
		}
	};
	const handleScroll = () => {
		// if (!scrollContainer.value) return;
		const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
		const clientHeight = window.innerHeight || document.documentElement.clientHeight;
		const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
		const distanceToBottom = scrollHeight - scrollTop - clientHeight;
		const isScrollDown = scrollTop > lastScrollTop.value;
	
		if (distanceToBottom <= 10 && isScrollDown) {
			loadMore();
		}
		lastScrollTop.value = scrollTop;
	};
	
	
	
	

	// 修改 onMounted 中的事件绑定
	onMounted(() => {
		getData(); // 初始加载
		window.addEventListener('scroll', handleScroll, true);
	});

	onUnmounted(() => {
		window.removeEventListener('scroll', handleScroll, true);
	});

	// 监听分类变化，重新加载
	watch(
		() => props.classifyId,
		async (newVal) => {
			if (newVal) {
				dataList.value.length = 0;
				if(props.classifyId == 91){
					localClassifyId.value = '';
				}else{
					localClassifyId.value = props.classifyId;
				}
				// console.log('props.classifyId',props.classifyId);
				pageInfo.value.page = 1; // 重置页码
				await getData();
				
			}
			// 分类变化后，强制滚动到顶部
			    
		}, {
			immediate: true
		}
	);

	// 打开详情页
	const goToDetail = debounce((courseId) => {
		router.push({
			name: 'home',
			query: {
				courseId: courseId
			}
		});
	}, 300);
	
	const reload = async () => {
	  // 重置分页状态（避免残留上次的页码）
	  pageInfo.value.page = 1;
	  dataList.value = [];
	  // 调用 getData 并返回 Promise，确保父组件 await 生效
	  return await getData(); 
	};
	
	// 关键：通过 defineExpose 暴露 reload 方法，让父组件能调用
	// defineExpose({
	//   // reload,
	//   getData
	// });
	// 关键：暴露 reload 方法给父组件
	defineExpose({
	  reload,
	  getData // 可选暴露，若父组件需直接调用 getData（不推荐，建议统一走 reload）
	});


	// defineExpose({
		
	// });
</script>

<style lang="scss" scoped>
	.index-tablist-box {
		/* 容器高度必须固定（根据页面实际情况调整，确保能滚动） */
		min-height: calc(100vh - 120px);
		// padding: 0 12.5px;
		display: inline-block;
		width: 100%;
		padding-bottom: 20px;
		// .scroll-container {
		// 	width: 100%;
		// 	height: 100%;
		// 	overflow-y: auto;
		// 	/* 允许纵向滚动 */
		// 	-webkit-overflow-scrolling: touch;
		// 	/* 优化移动端滚动体验 */
			
		// }

		.list-box {
			// margin-top: 10px;
			display: flex;
			flex-wrap: wrap;
			justify-content: flex-start;

			.itembox {
				width: calc(33.33% - 8px);
				margin-right: 12px;
				margin-bottom: 10px;

				&:nth-of-type(3n) {
					margin-right: 0;
				}
			}
		}

		
	}
	.load-status {
		padding: 20px 0;
		text-align: center;
		color: #666;
		font-size: 14px;
		background-color: transparent !important;
	}
	/* 骨架屏样式 */
	::v-deep .t-skeleton__row {
		margin-bottom: 20px;
		display: flex;
		gap: 10px;
	}

	::v-deep .t-skeleton__image {
		width: 100% !important;
		height: 160px !important;
		border-radius: 4px;
	}
</style>